<!-- 补库退货负责人 -->
<template>
    <div class="dialog-box">
        <el-dialog v-model="open" title="选择退货负责人" width="800" :close-on-click-modal="false" :destroy-on-close="true">
            <div class="dialog-content">
                <!-- 左侧组织架构 -->
                <div class="row-1">
                    <div class="row-1-title">
                        <div>组织架构</div>
                        <div style="cursor: pointer">
                            <el-icon>
                                <Search />
                            </el-icon>
                        </div>
                    </div>
                    <!-- 左侧组织架构树形列表 -->
                    <div class="row-1-content">
                        <el-tree style="max-width: 600px" :data="TreeData" :props="defaultProps" 
                            highlight-current="true" @node-click="handleNodeClick" />
                    </div>
                </div>

                <!-- 右侧人员列表 -->
                <div class="row-2">
                    <div class="table-container">
                        <el-table ref="leftTableRef" :data="tableData" style="width: 100%" border
                            :row-key="(row: User) => row.id" v-loading="loading">
                            <el-table-column width="55">
                                <template #default="scope">
                                    <el-radio v-model="selectedRowId" :label="scope.row.id"
                                        @change="handleRadioChange(scope.row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="姓名" property="name" width="auto" />
                            <el-table-column property="num" label="编号" width="auto" />
                            <el-table-column property="mobile" label="联系电话" show-overflow-tooltip width="auto" />
                        </el-table>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" color="#626aef" @click="submit" :disabled="!selectedRow">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';
import api from '@/api';

const emit = defineEmits(['selectManager']);

// 用户数据类型
interface User {
    name: string;
    num: string;
    Sphone: string;
    mobile: string;
    id: number;
}

// 组织架构树形数据类型
interface Tree {
    id: number;
    label: string;
    name: string;
    children?: Tree[];
}

const open = ref(false);
const selectedRowId = ref<number>();
const selectedRow = ref<User>();
const orgId = ref<number>();
const loading = ref(false);

// 组织架构数据
const TreeData = ref<Tree[]>([]);
const defaultProps = {
    children: 'children',
    label: 'name'
};

// 人员列表数据
const tableData = ref<User[]>([]);

// 获取组织架构树形列表
const getOrgTree = async () => {
    try {
        const res = await api.publicFun.getOrgList({});
        if (res.code === 200) {
            TreeData.value = res.data;
            console.log('获取组织架构:', res.data);
        } else {
            ElMessage.error(res.message || '获取组织架构失败');
        }
    } catch (error) {
        console.error('获取组织架构失败:', error);
        ElMessage.error('获取组织架构失败');
    }
};

// 获取组织人员 - 修改以支持预选择
const getOrgList = async () => {
    if (!orgId.value) return;
    
    loading.value = true;
    try {
        const res = await api.publicFun.getPurchasingDirectorList({
            org_id: orgId.value
        });
        if (res.code === 200) {
            tableData.value = res.data;
            console.log('获取组织人员:', res.data);
            
            // 检查是否有预选择的负责人需要匹配
            const preSelected = (window as any).preSelectedManager;
            if (preSelected && tableData.value.length > 0) {
                const matchedManager = tableData.value.find((user: User) => 
                    user.id === preSelected.id ||
                    user.name === preSelected.name ||
                    user.mobile === preSelected.phone ||
                    user.Sphone === preSelected.phone
                );
                
                if (matchedManager) {
                    selectedRowId.value = matchedManager.id;
                    selectedRow.value = matchedManager;
                    console.log('在当前组织中找到并选中预选负责人:', matchedManager);
                    
                    // 清除预选择信息
                    (window as any).preSelectedManager = null;
                }
            }
        } else {
            ElMessage.error(res.message || '获取人员列表失败');
            tableData.value = [];
        }
    } catch (error) {
        console.error('获取组织人员失败:', error);
        ElMessage.error('获取人员列表失败');
        tableData.value = [];
    } finally {
        loading.value = false;
    }
};

// 处理组织架构节点点击
const handleNodeClick = (data: Tree) => {
    console.log('选中组织:', data);
    orgId.value = data.id;
    // 清除之前的选择
    selectedRowId.value = undefined;
    selectedRow.value = undefined;
};

// 监听组织架构变化，获取对应人员
watch(orgId, () => {
    if (orgId.value) {
        getOrgList();
    }
});

// 处理单选按钮变化事件
const handleRadioChange = (row: User) => {
    selectedRow.value = row;
    console.log("选中退货负责人:", row);
};

// 处理取消按钮点击事件
const handleCancel = () => {
    open.value = false;
};

// 处理确认按钮点击事件
const submit = () => {
    if (selectedRow.value) {
        console.log("提交选中的退货负责人:", selectedRow.value);
        
        // 发送选中的负责人数据到父组件
        emit('selectManager', {
            id: selectedRow.value.id,
            name: selectedRow.value.name,
            phone: selectedRow.value.mobile || selectedRow.value.Sphone,
            num: selectedRow.value.num
        });
        
        open.value = false;
    } else {
        ElMessage.warning('请先选择一个负责人');
    }
};

// 打开弹窗
const openLoading = (currentManager?: any) => {
    // 重置选择状态
    selectedRowId.value = undefined;
    selectedRow.value = undefined;
    orgId.value = undefined;
    tableData.value = [];
    
    open.value = true;
    
    // 获取组织架构
    getOrgTree();
    
    // 如果有当前选中的负责人，保存起来用于后续匹配
    if (currentManager) {
        console.log('预选择的负责人:', currentManager);
        
        // 保存预选择的负责人信息，用于数据加载后进行匹配
        const preSelectedManager = {
            id: currentManager.id || currentManager.manager_id,
            name: currentManager.name || currentManager.manager_name,
            phone: currentManager.phone || currentManager.manager_phone
        };
        
        // 存储预选择信息，供数据加载后使用
        (window as any).preSelectedManager = preSelectedManager;
    } else {
        // 清除预选择信息
        (window as any).preSelectedManager = null;
    }
    
    console.log('打开退货负责人选择弹窗');
};

// 暴露方法
defineExpose({
    openLoading
});
</script>

<style lang="scss" scoped>
.dialog-content {
    display: flex;
    height: 400px;
    flex-direction: row;
    gap: 10px;

    .row-1 {
        flex: 1;
        border: 1px solid #f0f0f0;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .row-1-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            width: 76%;
            border-bottom: 1px solid #f0f0f0;
            margin: 0 auto;
            color: #172b4d;
            flex-shrink: 0;
        }

        .row-1-content {
            flex: 1;
            padding: 10px;
            margin: 0 10px;
            overflow-y: auto;
            overflow-x: hidden;
            max-height: calc(400px - 60px);

            &::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }

            &::-webkit-scrollbar-thumb {
                border-radius: 3px;
                background: #ddd;
                
                &:hover {
                    background: #999;
                }
            }

            &::-webkit-scrollbar-track {
                border-radius: 3px;
                background: #f5f5f5;
            }

            :deep(.el-tree) {
                background: transparent;
                
                .el-tree-node {
                    .el-tree-node__content {
                        height: 36px;
                        padding: 0 8px;
                        
                        &:hover {
                            background-color: #f5f7fa;
                        }
                    }
                    
                    .el-tree-node__expand-icon {
                        padding: 6px;
                        font-size: 12px;
                        
                        &.is-leaf {
                            color: transparent;
                            cursor: default;
                        }
                    }
                }
            }
        }
    }

    .row-2 {
        flex: 2;
        border: 1px solid #f0f0f0;
        width: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .table-container {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;

            &::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }

            &::-webkit-scrollbar-thumb {
                border-radius: 3px;
                background: #ddd;
                
                &:hover {
                    background: #999;
                }
            }

            &::-webkit-scrollbar-track {
                border-radius: 3px;
                background: #f5f5f5;
            }

            .el-table {
                height: 100%;
            }
        }
    }
}

::v-deep .el-dialog {
    --el-dialog-padding-primary: 0px;
    
    .el-dialog__body {
        padding: 20px 10px;
        overflow: hidden;
    }
}

::v-deep .el-dialog__header {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

::v-deep .dialog-footer {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #000;
}

:deep(.cell) {
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.el-radio__label) {
    display: none;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
    background: #6860ff;
    color: #6860ff;
}

:deep(.el-radio) {
    border-color: none;
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
    background-color: #edecff;
}

:deep(.el-tree-node__content) {
    height: 36px;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
    background-color: #edecff;
    color: #6860ff;
}

:deep(.el-radio__inner:hover) {
    border-color: #626aef;
}
</style>
